package com.mijie.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;


public class GeoUtil {
	private static Logger logger = Logger.getLogger(GeoUtil.class);
	
	private static final double EARTH_RADIUS = 6378.137 * 1000;//地球平均半径按米计算
	private static double rad(double d){
	   return d * Math.PI / 180.0;
	}

	//根据经纬度计算两点间距离
	public static double getDistance(double longitudeA,double latitudeA, double longitudeB, double latitudeB ){
	   double radLat1 = rad(latitudeA);
	   double radLat2 = rad(latitudeB);
	   double a = radLat1 - radLat2;
	   double b = rad(longitudeA) - rad(longitudeB);
	   double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + 
	    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	   s *= EARTH_RADIUS;
	   s = Math.round(s * 10000) / 10000;
	   return s;
	}
	
	public static double addDistance(double src,double meter){
		double second = meter / 30.9 / 3600 ;
		return src+second;
	}
	
	
	public static String baiduMapApi = "http://api.map.baidu.com/geocoder?output=json&key=4F014D0F0E1AAB4AFF420CB923F83640164573C0";
	public static String getAddress(double longitude,double latitude) {
		String content = null;
		String address = "";
		try {
			String url = baiduMapApi+"&location="+latitude+","+longitude;
			content = HttpUtil.request(url, "GET", "UTF-8", null);
			
			if(content!=null){
				JSONObject json = JSONObject.fromObject(content);
				String status = json.getString("status");
				
				if("OK".equalsIgnoreCase(status)){
					json = json.getJSONObject("result");
					address = json.getString("formatted_address");
				}
			}
		} catch (Exception e) {
			logger.error("content:"+content+","+e.getMessage(), e);
		}
		return address;
	}
	
	/**
	 * @param address
	 * @return double[]{lng,lat}
	 */
	public static double[] getLocationByAddress(String address){
		String content = null;
		double[] lnglat = null;
		if(address.trim().isEmpty()) return null;
		try {
			String url = baiduMapApi+"&address="+address;
			content = HttpUtil.request(url, "GET", "UTF-8", null);
			
			if(content!=null){
				JSONObject json = JSONObject.fromObject(content);
				String status = json.getString("status");
				
				if("OK".equalsIgnoreCase(status)){
					json = json.getJSONObject("result");
					JSONObject location = json.getJSONObject("location");
					if(location!=null){
						lnglat = new double[2];
						lnglat[0] = location.getDouble("lng");
						lnglat[1] = location.getDouble("lat");
					}
				}
			}
		} catch (Exception e) {
			logger.error("content:"+content+","+e.getMessage(), e);
		}
		return lnglat;
	}
	
	
	public static String[] SPECIAL_PROVINCES = {"内蒙古","黑龙江","广西","西藏","宁夏","新疆","台湾","香港","澳门"};
	public static Pattern CITY_PATTERN = Pattern.compile("自治州|布依族|土家族|蒙古族|哈尼族|景颇族|白族|回族|朝鲜族|版纳|傣族|傈僳族|藏族|彝族|苗族|羌族");
	public static String ip138 = "http://ip138.com/ips1388.asp?ip=";
	public static Pattern regionPattern = Pattern.compile("<li>本站主数据：(.*?)\\s+?.*?</li>");
	private static String[] citys = {"北京","天津","上海"};
	public static String[] getProvinceAndCity(String ip) {
		String content = null;
		String[] term = null;
		try {
			content = HttpUtil.request( ip138+ip+"&action=2", "GET", "GBK", null);
			Matcher m = regionPattern.matcher(content);
			if(m.find()){
				String region = null;
				int index = 0;
				region = m.group(1);
				for(String city : citys){
					if(region.indexOf(city)!=-1){
						term = new String[2];
						term[0] = city+"市";
						term[1] = term[0];
						break;
					}
				}
				if(term==null){
					index = region.indexOf("省");
					if(index!=-1){
						term = new String[2];
						term[0] = region.substring(0,index+1) ;
						index = region.indexOf("市");
						if(index!=-1){
							term[1] = region.substring(term[0].length(),index+1);
						}
					}
					
					index = region.indexOf("自治");
					if(index!=-1){
						term = new String[2];
						term[0] = region.substring(0,index+3) ;
						index = region.indexOf("市");
						if(index!=-1){
							term[1] = region.substring(term[0].length(),index+1);
						}
					}
					if(term!=null){
						if(term[0].equals("省份") || term[1].equals("城市")) term = null;
					}
				}//end of term
			}
		} catch (Exception e) {
			return null;
		}
		return term;
	}
	
}
